//
//  MYGDownloadUploadView.swift
//  MYDoctor
//
//  Created by Denny on 2024/4/8.
//

import UIKit
class MYGDownloadView: UIView {

     
    lazy var tableView: UITableView = {
        let control = UITableView.init(frame: .zero, style: .grouped)
        control.delegate = self
        control.dataSource = self
        control.rowHeight = UITableView.automaticDimension
        control.estimatedRowHeight = 85
        control.backgroundColor = .clear
        control.ww_foldable = true
        control.register(UINib.init(nibName: "MYGCloudDiskUploadDownloadCell", bundle: nil), forCellReuseIdentifier: "MYGCloudDiskUploadDownloadCell")
        control.register(UINib.init(nibName: "SafeRootTabHeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: "SafeRootTabHeaderView")
        return control
    }()
  
   
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.left.right.bottom.equalToSuperview()
        }
        NotificationCenter.default.addObserver(self, selector: #selector(downloadStateChange(_:)), name: CXDownloadConfig.stateChangeNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(downloadProgressChange(_:)), name: CXDownloadConfig.progressNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(addDownloadTask), name: Notification.Name("MYGCloudDiskDownloadController_addDownloadTask"), object: nil)
        tableView.reloadData()
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    @objc func addDownloadTask() {
        self.tableView.reloadData {
            DispatchQueue.main.asyncAfter(deadline: .now(), execute: {
                for (index,_) in MYGDownloadManager.shared.downlodingArray.enumerated() {
                    if let cell = self.tableView.cellForRow(at: IndexPath(item: index, section: 0)) as? MYGCloudDiskUploadDownloadCell {
                        cell.startDownload()
                    }
                }
            })
        }
    }
    
    
    
    @objc func downloadStateChange(_ noti: Notification) {
        guard let downloadModel = noti.object as? CXDownloadModel else {
            return
        }
        for (index, model) in MYGDownloadManager.shared.downlodingArray.enumerated() {
            if downloadModel.url == model.url {
                if downloadModel.state != .finish {
                    MYGDownloadManager.shared.downlodingArray[index] = downloadModel
                    tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .none)
                }else {
                    MYGDownloadManager.shared.updateDownloadModel(downloadModel) {
                        self.tableView.reloadData()
                    }
                }
               
                break
            }
        }
    }
    
    @objc func downloadProgressChange(_ noti: Notification) {
        guard let downloadModel = noti.object as? CXDownloadModel else {
            return
        }
        for (index, model) in MYGDownloadManager.shared.downlodingArray.enumerated() {
            if downloadModel.url == model.url {
                MYGDownloadManager.shared.downlodingArray[index] = downloadModel
                if let cell = tableView.cellForRow(at: IndexPath(item: index, section: 0)) as? MYGCloudDiskUploadDownloadCell {
                    cell.bind(model)
                    print("\(downloadModel.fileName ?? "")")
                }
                break
            }
        }
    }
}


extension MYGDownloadView:UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MYGCloudDiskUploadDownloadCell", for: indexPath) as! MYGCloudDiskUploadDownloadCell
        if indexPath.section == 0 {
            let model = MYGDownloadManager.shared.downlodingArray[indexPath.row]
            cell.bind(model)
        }else {
            let model = MYGDownloadManager.shared.downlodedArray[indexPath.row]
            cell.bind(model)
        }
        
        return cell
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SafeRootTabHeaderView") as! SafeRootTabHeaderView
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(gestureTapped(_:)))
        header.addGestureRecognizer(tapGesture)
        
        if section == 0 {
            header.contentLB.text = "进行中"
        }else {
            header.contentLB.text = "已完成"
        }
        header.tag = section
        header.isExtend = self.tableView.ww_isSectionFolded(section)
        return header
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return MYGDownloadManager.shared.downlodingArray.count
        }
        return MYGDownloadManager.shared.downlodedArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.1
    }
    @objc func gestureTapped(_ ges:UIGestureRecognizer) {
        guard let header = ges.view else {return}
        let section = header.tag
        self.tableView.ww_foldSection(section, fold: !self.tableView.ww_isSectionFolded(section))
    }
}


